package main

import (
	"fmt"
	"github.com/spf13/viper"
	"google.golang.org/grpc"
	"grpc/common/etcd"
	pb "grpc/common/pb/user"
	"grpc/user/global"
	"grpc/user/inits"
	"grpc/user/service"
	"net"
	"os"
)

func init() {
	v := viper.New()
	v.AddConfigPath("user/resource")
	v.SetConfigType("yaml")
	v.SetConfigName("config")
	if err := v.ReadInConfig(); err != nil {
		fmt.Println(err)
		os.Exit(0)
	}
	if err := v.Unmarshal(&global.Config); err != nil {
		fmt.Println(err)
		os.Exit(0)
	}
	inits.InitLogger()
	//inits.PgsqlDBConnect()
	//inits.RedisDBConnect()
	//inits.DBMigrate()
}

func main() {
	etcdRegister, err := etcd.NewEtcdRegister(global.Config.Etcd.Host + ":" + global.Config.Etcd.Port)
	if err!= nil{
		global.Logger.Fatal("etcd register failed: %v", err)
	}
	err = etcdRegister.ServiceRegister(global.Config.System.ServiceName, global.Config.System.ServiceAddr, 5)
	if err != nil {
		global.Logger.Fatal("etcd register failed: %v", err)
	}
	defer etcdRegister.Close()
	listen, err := net.Listen("tcp", global.Config.System.Port)
	if err != nil {
		global.Logger.Fatal("failed to serve: %v", err)
	}
	grpcServer := grpc.NewServer()
	defer grpcServer.Stop()
	pb.RegisterUserServer(grpcServer, service.GetUserSrv())
	global.Logger.Info("user service start... port", global.Config.System.Port)
	if err = grpcServer.Serve(listen); err != nil {
		global.Logger.Fatal("failed to serve: %v", err)
	}
}
